"use client";
import CreateModal from "./components/CreateModal";
import UpdateModal from "./components/UpdateModal";
import {
  deleteUserUsingPost,
  listUserByPageUsingPost,
} from "@/api/userController";
import { PlusOutlined } from "@ant-design/icons";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { PageContainer, ProTable } from "@ant-design/pro-components";
import { Button, message, Space, Typography, Modal } from "antd";
import React, { useRef, useState } from "react";

/**
 * 用户管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.User>();
  // 删除确认模态框显示状态
  const [deleteConfirmVisible, setDeleteConfirmVisible] = useState<boolean>(false);

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = (row: API.User) => {
    setCurrentRow(row);
    setDeleteConfirmVisible(true);
  };

  const handleConfirmDelete = async () => {
    const hide = message.loading("正在删除");
    if (!currentRow) {
      hide();
      return;
    }
    try {
      await deleteUserUsingPost({
        id: currentRow.id as any,
      });
      hide();
      message.success("删除成功");
      actionRef?.current?.reload();
      setDeleteConfirmVisible(false);
    } catch (error: any) {
      hide();
      message.error("删除失败，" + error.message);
      setDeleteConfirmVisible(false);
    }
  };

  const handleCancelDelete = () => {
    setDeleteConfirmVisible(false);
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.User>[] = [
    {
      title: "id",
      dataIndex: "id",
      valueType: "text",
      hideInForm: true,
    },
    {
      title: "账号",
      dataIndex: "userAccount",
      valueType: "text",
    },
    {
      title: "用户名",
      dataIndex: "userName",
      valueType: "text",
    },
    {
      title: "头像",
      dataIndex: "userAvatar",
      valueType: "image",
      fieldProps: {
        width: 64,
      },
      hideInSearch: true, //  不展示在搜索区
    },
    {
      title: "简介",
      dataIndex: "userProfile",
      valueType: "textarea",
    },
    {
      title: "权限",
      dataIndex: "userRole",
      valueEnum: {
        user: {
          text: "用户",
        },
        admin: {
          text: "管理员",
        },
      },
    },
    {
      title: "创建时间",
      sorter: true, //  支持排序
      dataIndex: "createTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true, //  不能被编辑
    },
    {
      title: "更新时间",
      sorter: true,
      dataIndex: "updateTime",
      valueType: "dateTime",
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => (
          //  record即传入的当前行的数据
          <Space size="middle">
            <Typography.Link
                onClick={() => {
                  setCurrentRow(record);
                  setUpdateModalVisible(true);
                }}
            >
              修改
            </Typography.Link>
            <Typography.Link type="danger" onClick={() => handleDelete(record)}>
              删除
            </Typography.Link>
          </Space>
      ),
    },
  ];

  return (
      <PageContainer>
        <ProTable<API.User>
            headerTitle={"查询表格"}
            actionRef={actionRef}
            rowKey="key"
            search={{
              //  搜索表格宽度
              labelWidth: 120,
            }}
            pagination={{
                style: { marginTop: 16, marginBottom: 24 }, // 分页器边距
            }}
            //  表格扩展工具部分
            toolBarRender={() => [
              <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    setCreateModalVisible(true);
                  }}
              >
                <PlusOutlined /> 新建
              </Button>,
            ]}
            //  用户操作请求
            request={async (params, sort, filter) => {
              const sortField = Object.keys(sort)?.[0];
              const sortOrder = sort?.[sortField] ?? undefined;

              const { data, code } = await listUserByPageUsingPost({
                ...params,
                sortField,
                sortOrder,
                ...filter,
              } as API.UserQueryRequest);

              return {
                success: code === 0,
                data: data?.records || [],
                total: Number(data?.total) || 0,
              };
            }}
            columns={columns}
        />
        <CreateModal
            //  创建用户弹窗
            visible={createModalVisible}
            columns={columns}
            onSubmit={() => {
              //  关闭弹窗
              setCreateModalVisible(false);
              //  刷新表格
              actionRef.current?.reload();
            }}
            onCancel={() => {
              setCreateModalVisible(false);
            }}
        />
        <UpdateModal
            //  更新用户弹窗
            visible={updateModalVisible}
            columns={columns}
            oldData={currentRow}
            onSubmit={() => {
              setUpdateModalVisible(false);
              setCurrentRow(undefined);
              actionRef.current?.reload();
            }}
            onCancel={() => {
              setUpdateModalVisible(false);
            }}
        />
        {/* 删除确认弹窗 */}
        <Modal
            title="删除用户"
            open={deleteConfirmVisible}
            onOk={handleConfirmDelete}
            onCancel={handleCancelDelete}
            okText="确认删除"
            cancelText="取消"
        >
          <p>你确定要删除这条记录吗？</p>
        </Modal>
      </PageContainer>
  );
};

export default UserAdminPage;